// 触摸面板类

var TouchPanelBase = cc.Layer.extend({

    // pri : 触摸优先级
    pri : 0,

    ctor:function (pri) {
        this._super();
        this.pri = pri;
    },

    onEnter:function () {
        //cc.log('TouchPanelBase.onEnter');
        //cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, this.pri, true);
        cc.registerTargettedDelegate(this.pri, true, this);
        this._super();
    },

    onExit:function () {
        //cc.log('TouchPanelBase.onExit');
        //cc.Director.getInstance().getTouchDispatcher().removeDelegate(this);
        cc.unregisterTouchDelegate(this);
        this._super();
    },

    onTouchBegan:function (touch, event) { cc.log('MUST override this function:onTouchBegan'); },
    onTouchMoved:function (touch, event) { cc.log('MUST override this function:onTouchMoved'); },
    onTouchEnded:function (touch, event) { cc.log('MUST override this function:onTouchEnded'); },
    onTouchCancelled:function (touch, event) { cc.log('MUST override this function:onTouchCancelled'); },

});



// 拖放面板
var DraggablePanelBase = TouchPanelBase.extend({

    // 拖放目标
    _dragTarget:null,
    _oldPos:null,

    getDragTarget:function () {
        return this._dragTarget;
    },

    // 拖放
    dragBegin:function (target) {
        this._dragTarget = target;
        this._oldPos = target.getPosition();
    },

    dragEnd:function (isReturnOldPos) {
        if(isReturnOldPos==undefined) isReturnOldPos = false;

        if(isReturnOldPos) this._targetReturn(this._dragTarget, this._oldPos);
        this._dragTarget = null;
        this._oldPos = null;
    },

    isDragging:function () {
        return (this._dragTarget != null);
    },

    // 目标返回初始位置
    _targetReturn:function (target, oldpos) {
        if (target) {
            var moveto = cc.MoveTo.create(0.3, oldpos);
            target.runAction(moveto);
        }
    },

    onTouchMoved:function (touch, event) {
        if (this._dragTarget) {
            var pos = this._dragTarget.getPosition();
            var delta = touch.getDelta();
            this._dragTarget.setPosition( cc.pAdd(pos, delta) );
        }
    },

    onTouchCancelled:function (touch, event) {
        if (this.isDragging()) this.dragEnd(true);
    },
});

